package com.huitone.smspfm.interfacz.tasks;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import com.huitone.smspfm.interfacz.core.AppStaticConfigs;
import com.huitone.smspfm.interfacz.logger.ExtLogger;
import com.huitone.smspfm.interfacz.model.MoDealHash;
import com.huitone.smspfm.redis.model.AppCanstant;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ABExcuteCommands;

public class PickOutResendDeliversTask extends Thread {
	
	private static final ExtLogger logger = ExtLogger.create(PickOutResendDeliversTask.class);
	
	private static final long excuteInterval = 100;
	
	private boolean keepGoing = true;

	@Override
	public void run() {
		
		@SuppressWarnings("rawtypes")
		RedisScript<List> script = new DefaultRedisScript<>(AppStaticConfigs.luaPickOutMo, List.class);
		
		List<String> keys = new ArrayList<>();
		keys.add(AppStaticConfigs.iSMMoDealSerialNoSet);
		keys.add(AppStaticConfigs.iSMMoRespSerialNoZSet);
		
		while(!this.isInterrupted() && isKeepGoing()) {
			
			List<List<String>> entities = AppStaticConfigs.scriptOpts2.getHashList(script, keys, "0", System.currentTimeMillis() + "", AppStaticConfigs.pickoutmoPerTime + "");
			
			List<MoDealHash> lists = new ArrayList<MoDealHash>();
			for (int i = 0 ; i < entities.size() ; i ++) {
				List<String> list = entities.get(i);
				MoDealHash entity = MoDealHash.parseStr(list);
				lists.add(entity);
			}
			
			if (!lists.isEmpty()) {
				AppStaticConfigs.pipelineOpts3.save(new ABExcuteCommands() {

					@Override
					public void excute(RedisConnection connection) {
						
						List<byte[]> resendList = new ArrayList<>();
						List<byte[]> failedList = new ArrayList<>();
						
						for (MoDealHash entity:lists) {
							
							int sendTimes = entity.getiSendTimes();
							
							if (sendTimes >= 3) {
								
								Map<byte[], byte[]> map = new HashMap<>();
								
								map.put(AppCanstant.SmsEntity.MoResult, AppStaticConfigs.stringRedisSerializer.serialize("1"));
								map.put(AppCanstant.SmsEntity.MoResultDesc, AppStaticConfigs.stringRedisSerializer.serialize("failed after 3 times resend option"));
								
								connection.hMSet(AppStaticConfigs.stringRedisSerializer.serialize(AppStaticConfigs.pSMCacheHash + ":" + entity.getiSMCacheKey()), map);
								
								failedList.add(AppStaticConfigs.stringRedisSerializer.serialize(entity.getiSMCacheKey()));
								
							} else {
								
								StringBuffer buffer = new StringBuffer();
								buffer.append(entity.getiSMCacheKey());
								buffer.append(":");
								buffer.append(entity.getiRptSnPart1());
								buffer.append(":");
								buffer.append(entity.getiRptSnPart2());
								buffer.append(":");
								buffer.append(entity.getiRptSnPart3());
								buffer.append(":");
								buffer.append(entity.getiSendTimes());
								
								resendList.add(AppStaticConfigs.stringRedisSerializer.serialize(buffer.toString()));
							}
						}
						
						if (!resendList.isEmpty()) {
							connection.lPush(AppStaticConfigs.iSMMoResendListB, resendList.toArray(new byte[1][]));
						}
						
						if (!failedList.isEmpty()) {
							byte[][] bs = failedList.toArray(new byte[1][]);
							connection.lPush(AppStaticConfigs.iSMMoDealFailedListB, bs);
							connection.lPush(AppStaticConfigs.iSMMoEndListB, bs);
						}
					}
				});
			}
			
			try {
				Thread.sleep(excuteInterval);
			} catch (InterruptedException e) {
				break;
			}
		}
		
		logger.info("推送报告超时无响应检测任务退出!");
	}

	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
	}

}
